/*
@STI LICENSE
(C) 2006-2008 Universit�t Innsbruck.

This file is part of myOntology.

myOntologyis free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

myOntologyis distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with myOntology.  If not, see <http://www.gnu.org/licenses/>.

@STI LICENSE */
package view.servlets;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.util.Streams;
import org.apache.commons.io.FilenameUtils;
import org.apache.log4j.Logger;
import org.myontology.users.Login;

public class FileUpload extends HttpServlet {

	private static final long serialVersionUID = 1L;

	public static Logger logger = Logger.getLogger(FileUpload.class);
	
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
			
		
		if ( !Login.LOGGED_IN.getValue(request) ) {			
			response.sendRedirect( request.getContextPath() + "/login");
			return;
		}
			
        //check, that it is a multipart-request
        if( !ServletFileUpload.isMultipartContent(request) )
            return;
        
        String toImportPath = null;
        
        //Retrieve Context
        ServletContext application = this.getServletContext();
             
	    //Create new UploadHandler
        ServletFileUpload upload = new ServletFileUpload();
        
        try {
            FileItemIterator iter = upload.getItemIterator(request);
            File file = null;       
            while (iter.hasNext()) 
            {
                FileItemStream item = iter.next();
                String name = item.getFieldName();
                InputStream stream = item.openStream();
                
                //Is Item a POST-variable?
                if ( item.isFormField() )
                {  
                	if( name.equals("fileURI") ) {
                		
                		// file auf Server laden:
                		String param = Streams.asString( stream );

						URL url = new URL( param );
						URLConnection urlconn = url.openConnection(); 
						  
						InputStream urlconninstr = urlconn.getInputStream(); 
						InputStreamReader isr = new InputStreamReader( urlconninstr ); 
						BufferedReader br = new BufferedReader( isr ); 
                		
                        //inputFile=context.getInitParameter("SKOS2GenTaxDataDirectory") + File.separator + "uploads" + File.separator + fileName;
						if( param.charAt( param.length()-1 ) == '/') {
							
							param = param.substring(0, param.length()-1);
						}
						String fileName = param.substring( param.lastIndexOf('/') + 1 );
						String FileNameURL=application.getInitParameter("ImportFileDirectory") + File.separator + request.getSession().getId() + File.separator + fileName;
                        //Create file in temporary directory
                        File dir = new File( application.getInitParameter("ImportFileDirectory") + File.separator + request.getSession().getId() );
                        dir.mkdirs();
                        
                        File URLFile = new File(FileNameURL);
                        URLFile.createNewFile();
						//FileWriter fw = new FileWriter(URLFile); 
						FileOutputStream os = new FileOutputStream(URLFile, false);
						OutputStreamWriter fw = new OutputStreamWriter(os);
						BufferedWriter bw = new BufferedWriter(fw);
						
						String zeile = br.readLine(); 
						while (zeile != null) { 
							bw.write(zeile); 
							bw.newLine(); 
							zeile = br.readLine(); 
						} 
						
						br.close(); 
						bw.close();
                        
                        toImportPath = FileNameURL;
                    }
                }
                else
                {                    
                    //IE submits complete path of the uploading file - convert
                    String fileName = FilenameUtils.getName( item.getName() );
                    // fileExtension=FilenameUtils.getExtension(item.getName()).toLowerCase();
                    //System.out.println("extension:"+fileExtension);
                    
                    if (fileName.equals("")) {

                    	String tmp = request.getContextPath() + "/OWLimportError.do";
                    	response.sendRedirect( tmp );
                    	return;
                    }     
     
//                    String dirString = getServletContext() + File.separator + context.getInitParameter("ImportFileDirectory") + File.separator + request.getSession().getId();
                    String dirString = application.getInitParameter("ImportFileDirectory") + File.separator + request.getSession().getId();
                    //Create file in temporary directory
                    File dir = new File( dirString );
                    dir.mkdirs();
                    
                    String inputFile = dirString + File.separator + fileName;
                    file = new File( inputFile );
                    file.createNewFile();
                    
                    BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(file));

                    //Receive file
                    byte buf[] = new byte[4096];
                    int len = 0;
                    
                    while( ( len = stream.read( buf ) ) > 0 ) 
                    {                        
                        //Write data
                        out.write( buf, 0, len );
                    }
                    
                    out.close();
                    
                    toImportPath = inputFile;
                }                
            }
                        
            if( toImportPath!=null ) {
            	
            	HttpSession session = request.getSession();
            	
            	session.setAttribute( "toImportPath", toImportPath);
            	
            	String tmp = request.getContextPath() + "/OWLimportValidate.do";
            	response.sendRedirect( tmp );
            	return;
            }           
        }
        /*catch (FileNotFoundException e) {
        } catch (IOException e) {
        } catch (FileUploadException e) {
    	}*/ catch (Exception e) {
    		logger.error(e);
    	}


    	String tmp = request.getContextPath() + "/OWLimportError.do";
    	response.sendRedirect( tmp );
    	return; 
    }
    

    
}

